package com.system.xingzhi.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.system.xingzhi.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {

    private static final Logger logger = LoggerFactory.getLogger(JwtUtil.class);

    /*
    *  过期时间
    * */
    private static final long EXPIRATION = 60*60;//单位毫秒

    /*
    *  生成Token
    * */
    public  String creatToken(User user){
        Date expireDate = new Date(System.currentTimeMillis() + EXPIRATION * 1000);
        Map<String,Object> map = new HashMap<>();
        map.put("alg","HS256");
        map.put("typ","jwt");
        String token = JWT.create()
                .withHeader(map)
                .withClaim("id",user.getUserId())
                .withClaim("username",user.getUserName())
                .withClaim("expireDate",expireDate)
                .withExpiresAt(expireDate)
                .withIssuedAt(new Date())
                .sign(Algorithm.HMAC256(user.getPassword()));
        return token;
    }

    /*
    *  验证token是否过期，临近过期刷新token
    * */
    public  Map<String,String> verifyToken(String token,User user){
        DecodedJWT jwt = null;
        Map<String,String> map = new HashMap<>();
        if (token == null){
            map.put("status","token值为空");
            return map;
        }
        if (user==null){
            map.put("status","未找到用户,请重新登陆");
            return map;
        }
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
            jwt = verifier.verify(token);
        }catch (Exception e) {
            logger.info("用户:" + user.getUserName()+"  id:"+ user.getUserId()
                    +"   token已失效");
            map.put("status","token失效");
            return map;
        }
        map.put("status","验证成功");
        if ((jwt.getClaim("expireDate").asDate().getTime()-(new Date()).getTime()) < 600000){
           map.put("newToken",creatToken(user));
        }
        return map;
        }
    }

